package cn.new18.testactivitytask.base;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.google.gson.Gson;
import com.lzy.okgo.callback.AbsCallback;

import org.json.JSONObject;

import java.lang.reflect.Type;

import cn.new18.testactivitytask.R;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by RaoWei on 2016/11/22 11:51.
 */

public abstract class LazyFragment extends Fragment {
    private static final String TAG = "LazyFragment";
    private boolean isFirstResume = true;
    private boolean isFirstVisible = true;
    private boolean isFirstInvisible = true;
    private boolean isPrepared;
    public LoadingPage mLoadingPage;
    private Object o;

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initPrepare();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mLoadingPage == null) {
            mLoadingPage = new LoadingPage(getContext()) {
                @Override
                protected void onErrorLoadAgain() {
                    OnErrorImgClick();
                }

                @Override
                protected View creatSuccessView() {
                    return setContainerView();
                }
            };
        }
        return mLoadingPage;
    }

    protected abstract void OnErrorImgClick();


    public abstract class LoadingViewCallBack<T> extends AbsCallback<T> {

        private Class<T> clazz;
        private Type type;
        private Context mContext;
        protected abstract void onLoadSuccess(T t);

        public LoadingViewCallBack (Class<T> clazz){
            this.clazz = clazz;
        }

        public LoadingViewCallBack (Type type){
            this.type = type;
        }


        @Override
        public void onSuccess(T t, Call call, Response response) {
            mLoadingPage.mState = LoadingPage.PageState.STATE_SUCCESS;
            if (t != null) {
                o = t;
            }
            onLoadSuccess(t);
        }

        @Override
        public T convertSuccess(Response response) throws Exception {

            String responseData = response.body().string();
            if (TextUtils.isEmpty(responseData)) {//如果为空
                return null;
            }
            //解析json
            JSONObject jsonObject = new JSONObject(responseData);
            final int code = jsonObject.optInt("code", 0);
            final String message = jsonObject.optString("message", "");
            String result = jsonObject.optString("data", "");
            if (code == 0) {
                if (type != null) {
                    return new Gson().fromJson(result, type);
                }
                if (clazz == String.class) {
                    return (T) message;
                }
                    return new Gson().fromJson(result, clazz);
            }
            else {
                //如果要更新UI，需要使用handler，可以如下方式实现，也可以自己写handler
                //OkGo.getInstance().getDelivery().post(() ->
                //        ToastUtil.showShort(OkGo.getContext(), message));
                throw new IllegalStateException("错误代码：" + code + "，错误信息：" + message);
            }
        }

        @Override
        public void onError(Call call, Response response, Exception e) {
            super.onError(call, response, e);
            mLoadingPage.mState = LoadingPage.PageState.STATE_ERROR;
        }

        @Override
        public void onAfter(T t, Exception e) {
            super.onAfter(t, e);
            mLoadingPage.showPage();
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        Log.e(TAG, "onResume");
        Log.e(TAG, "isFirstResume = " +isFirstResume + "getUserVisibleHint() = " + getUserVisibleHint());
        if (isFirstResume) {
            isFirstResume = false;
            return;
        }
        if (getUserVisibleHint()) {
            onUserVisible();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.e(TAG, "onPause");
        if (getUserVisibleHint()) {
            onUserInvisible();
        }
    }

    /**
     * 在viewpager左右滑动切换的时候被调用
     * @param isVisibleToUser
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        Log.e(TAG, "isVisibleToUser = " + isVisibleToUser);
        if (isVisibleToUser) {
            if (isFirstVisible) {
                isFirstVisible = false;
                initPrepare();
            } else {
                onUserVisible();
            }
        } else {
            if (isFirstInvisible) {
                isFirstInvisible = false;
                onFirstUserInvisible();
            } else {
                onUserInvisible();
            }
        }
    }


    /**
     * 第一次对用户不可见（暂时不使用）
     */
    private void onFirstUserInvisible() {

    }

    /**
     * 初始化显示
     */
    private synchronized void initPrepare() {
        if (isPrepared) {
            if (o != null) {
                mLoadingPage.mState = LoadingPage.PageState.STATE_SUCCESS;
                mLoadingPage.showPage();
                return;
            }
            onFirstUserVisible();
        } else {
            isPrepared = true;
        }
    }

    /**
     * 第一次对用户可见时调用
     */
    protected abstract void onFirstUserVisible();

    /**
     * 对用户不可见时调用
     */
    protected abstract void onUserInvisible();

    /**
     * 对用户可见时调用
     */
    protected abstract void onUserVisible();

    /**
     * 设置请求网络成功后自定义布局
     */
    protected abstract View setContainerView();
}
